<?php

namespace App\Task\Crontab;

use App\Dao\UserDao;
use App\Job\Auto\ChatResQueueJob;
use App\Model\User;
use App\Utils\LoggerUtil;
use App\Utils\RedisClient;
use Hyperf\Crontab\Annotation\Crontab;

/**
 * Note - 主播对在线用户自动聊天
 * DateTime 2024/9/2 12:30
 * User Admin
 * Class AutoChatTask
 * @package App\Task\Crontab
 */
// #[Crontab(name: "AutoChat", rule: "*/10 * * * *", callback: "execute", memo: "自动聊天任务")]
class AutoChatTask
{
    public function execute()
    {
        // 获取所有在线的男性用户
        $onlineUsers = UserDao::getInstance()->getOnlineMaleUids();
        if (!empty($onlineUsers)) {
            $redis = RedisClient::getInstance();
            // 获取所有审核环境的uid
            $auditUids = UserDao::getInstance()->getAuditUidsEx();
            $users = array_diff($onlineUsers, $auditUids);
            foreach ($users as $uid) {
                $rs = $redis->hGet('auto_chat_res', strval($uid));
                $intervals = [0, 10, 20, 30, 40, 120, 180, 240, 300, 360, 420, 480, 540];
                if (empty($rs)) {
                    $data = [
                        'uid' => $uid,
                        'users' => []
                    ];
                    foreach ($intervals as $interval) {
                        $data['time'] = $interval;
                        pushDelayJob(ChatResQueueJob::class, $data, $interval);
                    }
                    $redis->hSet('auto_chat_res', strval($uid), json_encode($data));
                } else {
                    $data = json_decode($rs, true);
                    $users = $data['users'] ?? [];
                    if (count($users) > count($intervals)) {
                        $redis->hDel('auto_chat_res', strval($uid));
                    }
                    LoggerUtil::write('index', 'already exists');
                }
            }
            User::query()->whereIn('id', $onlineUsers)->update(['auto_chat_online' => 0]);
        } else {
            LoggerUtil::write('index', 'no online male users');
        }
    }

}